<?php
class DBUpdater
{
	private $tv;
	private $multicurl;
	private $updated;

	public function __construct()
	{
		$this->tv = new TheTvDB;
		$this->updated = array('series' => array(), 'episodes' => array());
		$this->multicurl = new updatercurl();
		$this->multicurl->setOpt(CURLOPT_ENCODING, 'gzip,deflate');

		try {
		    //ini_set('max_execution_time', 600);
    		$updatesList = $this->tv->getApi()->loadUpdatesList();

            $this->updateType($updatesList, 'series');
    		$this->multicurl->reset();
    		$this->updateType($updatesList, 'episodes');

    		$this->tv->savePreviousTime($updatesList['servertime']);

    		ob_flush();
		    flush();
		} catch (Exception $e) {
		    echo $e->getMessage();
		}
	}

	protected function updateType($source, $type = 'series')
	{
	    $api = $this->tv->getApi();
	    foreach($source[$type] as $item_id) {
	        $url = $api->getLink($item_id, $type);
	        if ($type == 'series' && !$this->tv->isSeriaIsset($item_id)) {
	            continue;
	        }
	        $this->multicurl->addUrl($url, $item_id);
		}

	    foreach ($this->multicurl->getResult() as $id => $content) {
		    $xml = @simplexml_load_string($content);
		    if ($xml === false) {
		        throw new Exception('Nem sikerült megnyitni a letöltött XML fájlt! (' . $type . ': ' . $id , ')', 403);
		    }
		    $func = $type == 'series' ? 'insertSeria' : 'insertEpisode';
		    $data = $api->xmlFieldFilter($xml, $api->getFieldFilter($type));
		    if ($this->tv->$func($data[0]) !== false) {
		        echo "A\t{$type}: {$id}\n";
		        $this->updated[$type][] = $id;
		    }
		}
	}

	public function getUpdated()
	{
	    return $this->updated;
	}
}
?>